import Vue from 'vue'
import $ from 'jquery'
Vue.directive('filterSpecialChar', {
  update: function(el, {
    value,
    modifiers
  }, vnode) {
    try {

      let newval = value.replace(/\s+/g, '');
      //let newval = value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, "");
      if (value !== newval) {
        el.children[0].value = newval
        el.children[0].dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
      }
    } catch (e) {
      console.log(e)
    }
  }
})

Vue.directive('thousands', {
  bind(el, binding, vnode) {
      const key = Object.keys(binding.modifiers)[0]
      // 处理千分位展示
      const generatingThousandthPer = (num) => {
        // num = num.replace(/\s+/g,'');空格
        var t = num.charAt(0);
        num = num.replace(/[^\d.]/g, "");
        //必须保证第一个为数字而不是.
        num = num.replace(/^\./g, "");
        //保证只有出现一个.而没有多个.
        num = num.replace(/\.{2,}/g, ".");
        //保证.只出现一次，而不能出现两次以上
        num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        //如果第一位是负号，则允许添加  如果不允许添加负号 可以把这块注释掉
        if (t == '-') {
          num = '-' + num;
        }
        let num1 = num.split(".")[0],
          num2 = num.split(".")[1];
        let c = num1.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        return num.toString().indexOf(".") !== -1 ? c + "." + num2 : c;
      }
      // 赋值
      const assignment = (event, value, value2) => {
        binding.value[key] = value;
        vnode.context.$nextTick(() => event.target.value = generatingThousandthPer(value2 || value))
      }
      // 处理最后一位非法字符
      const handlerIllegalStr = (str) => {
        while (!(/^[0-9]+.?[0-9]*/.test(str.charAt(str.length - 1)))) {
          str = str.substr(0, str.length - 1)
        }
        return str
      }
      el.addEventListener("input", (event) => {
        let inp = event.target.value = event.target.value.replace(/,/g, "")
        assignment(event, inp)
      })
      // element
      const input = $(el).find(".el-input__inner")
      if (input) {
         // console.log($(input[0])
        input[0].addEventListener("blur", (event) => {
          const val = event.target.value;
          if (!val || !/^[0-9]+.?[0-9]*/.test(val)) {
            event.target.value = ''
          }
           return '';
          assignment(event, handlerIllegalStr(val.replace(/,/g, "")))
        })
      }
  }
})
